package me.may.money;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

import org.bukkit.Bukkit;
import org.bukkit.plugin.ServicePriority;
import org.bukkit.plugin.java.JavaPlugin;

import me.may.money.api.MoneyAPI;
import me.may.money.command.MoneyCommandHandler;
import me.may.money.dao.BasicDao;
import me.may.money.listener.PlayerJoinListener;
import net.milkbowl.vault.Vault;
import net.milkbowl.vault.economy.Economy;

/**
 * 插件主类
 * 
 * @author May_Speed
 */
public class Entry extends JavaPlugin {
	
	private static Entry instance;
	
	public void onEnable() {
		saveDefaultConfig();
		try {
			//指定连接类型
			Class.forName("com.mysql.jdbc.Driver");
			String host = getConfig().getString("Mysql.Host");
			String port = getConfig().getString("Mysql.Port");
			String dbname = getConfig().getString("Mysql.DataBase");
			String username = getConfig().getString("Mysql.User");
			String password = getConfig().getString("Mysql.PassWord");
			String ip = "jdbc:mysql://" + host + ":" + port + "/" + dbname + "?autoReconnect=true";
			String sql = "CREATE TABLE IF NOT EXISTS playerMoney (" + 
					"id int(11) NOT NULL AUTO_INCREMENT," +
					"playerName varchar(255) DEFAULT NULL," +
					"money double(12,2) DEFAULT NULL," + 
					"PRIMARY KEY(id) ) " + 
					"ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 ;";
			Connection conn = DriverManager.getConnection(ip, username, password);
			Statement st = conn.createStatement();
			st.executeUpdate(sql);
			BasicDao.setConnection(conn);
			Bukkit.getConsoleSender().sendMessage("§8[§6交子§8] §e>> §f数据库连接成功!");
		} catch (Exception e) {
			System.out.println("错误: " + e.getMessage());
			Bukkit.getConsoleSender().sendMessage("§8[§6交子§8] §e>> §f数据库连接失败!");
			Bukkit.getPluginManager().disablePlugin(this);
		}
		instance = this;
		Bukkit.getPluginManager().registerEvents(new PlayerJoinListener(), this);
		Bukkit.getPluginCommand("money").setExecutor(new MoneyCommandHandler());
		setUpEconomy();
	}
	
	public void onDisable() {
		if (!BasicDao.isClose()) {
			BasicDao.close();
		}
		Bukkit.getConsoleSender().sendMessage("§8[§6交子§8] §e>> §f数据库链接关闭成功!");
	}
	
	public static Entry getInstance() {
		return instance;
	}
	
	private void setUpEconomy() {
		try {
			Vault vault = (Vault) Bukkit.getPluginManager().getPlugin("Vault");
			Economy econ = (Economy) new MoneyAPI();
		    Bukkit.getServicesManager().register(Economy.class, econ, vault, ServicePriority.Highest);
		    vault.getLogger().info(String.format("[Economy] MayMoney: %s", new Object[] { econ.isEnabled() ? "已加载" : "等待加载中..." }));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
